package com.x.erp.manage;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.x.erp.dao.*;
import com.x.erp.model.*;
import com.x.erp.util.ConstantTopic;
import com.x.framework.exception.BusinessException;
import com.x.framework.exception.ExceptionCode;
import com.x.framework.manage.BaseManage;
import com.x.framework.remote.HttpClient;
import com.x.rocketmq.RocketMqProducer;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class CarManage extends BaseManage {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CarDao carDao;// 车辆DAO

	@Autowired
	private ModelDao modelDao;// 车型DAO

	@Autowired
	private CarImageDao carImageDao;// 车辆ImageDAO

	@Autowired
	private FastFileStorageClient fdfsClient;//文件服务

	@Autowired
	private CarConfInfoDao carConfInfoDao;// 车辆配置Dao

	@Autowired
	private CarOrderDao carOrderdao;// 车辆预订

	@Autowired
	private CarValuationDao carValuationDao;// 车辆估值DAO
	
	@Autowired
	private ImageViewDao imageViewDao;// 图片场景服务
	
	@Autowired
	private RocketMqProducer rocketMqProducer;

	@Autowired
	private HttpClient httpClient;

	/**
	 * 新增车辆信息
	 * @param car
	 * @return
	 * @throws Exception
	 */
	public Car insertCar(Car car) throws Exception {
		logger.info("carJson=================" + JSON.toJSONString(car));
		// 查询车型里的新车指导价，赋值给车辆
		Model modelTemp = new Model();
		modelTemp.setModelId(car.getModelId());
		modelTemp = modelDao.selectModelList(modelTemp).get(0);
		car.setCarGuidePrice(modelTemp.getModelGuidePrice());

		Date cDate = this.getDate(0);
//		car.setCarCreateTime(cDate);
		car.setCarUpdateTime(cDate);
		createCarNo(car);
		this.insert(car);
		String carId = car.getCarId();
		//处理图片信息
		List<CarImage> carImages = car.getCarImages();
		CarImage carImage = new CarImage();
		carImage.setCarId(car.getCarId());
		// 批量生成carImage对象
		carImageDao.insertCarImageList(carImage, carImages);
//		if(carImages != null) {
//			for(CarImage image : carImages) {
//				//处理空url
//				if(StringUtils.isNotEmpty(image.getImageUrl())) {
//					image.setCarId(carId);
//					image.setImageCreateTime(cDate);
//					this.insert(image);
//				}
//			}
//		}
		//批量插入配置信息
		String[] carConfIds = car.getCarConfIds();
		CarConfInfo carCarConfInfo = new CarConfInfo();
		carCarConfInfo.setCarId(car.getCarId());
		carConfInfoDao.insertCarConfInfoList(carCarConfInfo, carConfIds);
//		if(carConfIds != null) {
//			CarConfInfo carCarConf = new CarConfInfo();
//			carCarConf.setCarId(carId);
//			for(String carConfId : carConfIds) {
//				carCarConf.setConfId(Integer.valueOf(carConfId));
//				this.insert(carCarConf);
//			}
//		}
		//处理估值信息
		List<CarValuation> carValuations = car.getCarValuations();
		if (carValuations != null && carValuations.size() > 0){
			carValuationDao.insertCarValuationList(car.getCarId(), carValuations);
		}
		//记录日志信息
		List<CarLog> carLogs = car.getCarLogs();
		if(carLogs != null) {
			for(CarLog carLog :carLogs) {
				carLog.setCarId(carId);
				this.insert(carLog);
			}
		}
		return car;
	}

	private void createCarNo(Car car) throws Exception {
		String carNo;
		int randomNum;
		Car carTemp = new Car();
		for(;;){
			randomNum = (int)(Math.random ()*Math.pow (10,8));
			carNo = String.format ("%010d",randomNum);
			carTemp.setCarNo (carNo);
			carTemp = carDao.selectCar (carTemp);
			if(carTemp == null){
				break;
			}
		}
		car.setCarNo (carNo);
	}

	/**
	 * 修改车辆信息
	 * @param car
	 * @return
	 * @throws Exception 
	 */
	public int updateCarInfo(Car car) throws Exception {
		int res = updateCar (car);
		try {
			rocketMqProducer.produceMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_UPDATE_CAR_INFO, car);
		} catch (Exception e) {
			logger.error("修改车辆信息插入rocketMq队列异常", e);
			throw new BusinessException(ExceptionCode.EXCEPTION_CODE0003, e);
		}
		return res;
	}

	private int updateCar(Car car) throws Exception {
		logger.info("carJson=================" + JSON.toJSONString(car));
		Date cDate = this.getDate(0);
		car.setCarUpdateTime(cDate);
		int res = this.update(car);
		List<CarImage> carImages = car.getCarImages();
		if(carImages != null && carImages.size() > 0) {
			//查询原先使用场景为（2:含VIN详情）的图片
			CarImage carImage = new CarImage();
			carImage.setCarId(car.getCarId());
			List<CarImage> selectCarImages = carImageDao.selectCarImageList(carImage, 2);
			//批量从数据库删除车辆图片信息（2:含VIN详情）
			carImageDao.deleteCarImageList(carImage, 2);
			// 批量生成carImage对象
			carImageDao.insertCarImageList(carImage, carImages);

			//将原有的图片URL中使用场景为（3:不含VIN详情）放入set集合中，记录需要从文件库删除的URL
			Set<String> imageUrls = new HashSet<> ();
			for(CarImage ci : selectCarImages){
				imageUrls.add(ci.getImageUrl());
			}
			//过滤需要熊文件库删除的车辆图片信息
			for(CarImage image : carImages) {
				if(StringUtils.isNotEmpty(image.getImageUrl())) {
					//如果set集合中有该URL，将其移除，不需要从文件库删除
					imageUrls.remove(image.getImageUrl());
				}
			}

			//将set集合中被舍弃掉的图片URL从文件库删除
			try {
				for(String imageUrl : imageUrls){
					if(StringUtils.isNotEmpty(imageUrl)){
						fdfsClient.deleteFile(imageUrl);// 删除图片文件
					}
				}
			} catch (Exception e) {
				logger.error("删除车辆，删除图片文件出错", e);
			}
		}
		if(car.getCarConfIds() != null) {
			//删除原有配置关系
			CarConfInfo carCarConfInfo = new CarConfInfo();
			carCarConfInfo.setCarId(car.getCarId());
			this.delete(carCarConfInfo);
			//批量插入配置信息
			String[] carConfIds = car.getCarConfIds();
			carConfInfoDao.insertCarConfInfoList(carCarConfInfo, carConfIds);
		}
		//处理车辆估值信息
		List<CarValuation> carValuations = car.getCarValuations();
		if (carValuations != null && carValuations.size() > 0){
			carValuationDao.deleteCarValuationList(car.getCarId());
			carValuationDao.insertCarValuationList(car.getCarId(), carValuations);
		}
		//记录日志信息
		List<CarLog> carLogs = car.getCarLogs();
		if(carLogs != null) {
			for(CarLog carLog :carLogs) {
				this.insert(carLog);
			}
		}
		return res;
	}

	/**
	 * 修改车辆状态
	 * @param car
	 * @return
	 * @throws Exception
	 */
	public int updateCarState(Car car) throws Exception {
		int res = updateCar (car);
		return res;
	}


	/**
	 * 删除车辆信息
	 * @param car
	 * @return
	 */
	public int deleteCar(Car car) throws Exception {
		// 删除文件库车辆图片
		CarImage carImage = new CarImage();
		carImage.setCarId(car.getCarId());
		List<CarImage> carImages = carImageDao.selectCarImageByCarId(carImage);
		if(carImages != null && carImages.size() > 0){
			for (CarImage image : carImages){
				try {
					fdfsClient.deleteFile(image.getImageUrl());// 删除图片文件
				}catch (Exception e){
					logger.error("删除车辆，删除图片文件出错", e);
				}
			}
		}
		//删除图片信息
		carImageDao.execute("DELETE FROM ERP_CAR_IMAGE WHERE CAR_ID = ?", car.getCarId());
		//删除车辆配置信息
		carConfInfoDao.execute("DELETE FROM ERP_CAR_CONF_INFO WHERE CAR_ID = ? ", car.getCarId());
		//删除车辆预订信息
		carOrderdao.execute("DELETE FROM ERP_CAR_ORDER WHERE CAR_ID = ? ", car.getCarId());
		//删除车辆销售信息
		carOrderdao.execute("DELETE FROM ERP_CAR_SALE WHERE CAR_ID = ? ", car.getCarId());

		//记录日志信息
		List<CarLog> carLogs = car.getCarLogs();
		if(carLogs != null) {
			for(CarLog carLog :carLogs) {
				this.insert(carLog);
			}
		}
		try {
			rocketMqProducer.produceMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_CAR_DELETE_CAR_INFO, car);
		} catch (Exception e) {
			logger.error("删除车辆信息插入rocketMq队列异常", e);
		}
		//删除车辆信息
		Car deleteCar = new Car();
		deleteCar.setCarId(car.getCarId());
		return carDao.delete(deleteCar);
	}
	
	/**
	 * 绑定RFID
	 * @param car
	 * @param carCard
	 * @return
	 */
	public int updateCarBindRfid(Car car, String carCard) throws Exception {
		int res = this.update(car);
		//记录日志信息
		List<CarLog> carLogs = car.getCarLogs();
		if(carLogs != null) {
			for(CarLog carLog :carLogs) {
				this.insert(carLog);
			}
		}
//		String resStr = httpClient.doPostJson(Constant.JS_GATE_SAVE_CARD_RFID_PATH,"{\"carCard\":\"" + carCard + "\",\"carRfid\":\"" + car.getCarRfid() + "\",\"marketId\":\"" + car.getMarketId() +"\"}");
//		JSONObject resObj = JSON.parseObject(resStr);
//		if(!resObj.getJSONObject("result").getBoolean("saveOK")) {
//			throw new BusinessException("捷顺停车场系统换卡异常：" + resObj.getJSONObject("result").getString("message"));
//		}
		return res;
	}

	/**
	 * 修改车辆抵押状态
	 * @param car
	 * @return
	 * @throws Exception
	 */
	public int updateCarOfPledge(Car car) throws Exception {
		logger.info("carJson=================" + JSON.toJSONString(car));
		Date cDate = this.getDate(0);
		car.setCarUpdateTime(cDate);
		int res = this.update(car);
		List<CarImage> carImages = car.getCarImages();
		if(car.getCarImages() != null) {
			//插入图片
			CarImage carImage = new CarImage();
			CarImage carImage1 = new CarImage();
			carImage.setCarId(car.getCarId());
			for(CarImage image : carImages) {
				carImage.setImageKey(image.getImageKey());
				List<CarImage> selectCarImageList = carImageDao.selectCarImageList(carImage, null);
				if(selectCarImageList != null && selectCarImageList.size() > 0){
					String imageId = selectCarImageList.get(0).getImageId();
					carImage1.setImageId(imageId);
					carImage1.setImageUrl(image.getImageUrl());
					this.update(carImage1);
				}else{
					image.setCarId(car.getCarId());
					image.setImageCreateTime(cDate);
					this.insert(image);
				}
			}
		}
		//记录日志信息
		List<CarLog> carLogs = car.getCarLogs();
		if(carLogs != null) {
			for(CarLog carLog :carLogs) {
				this.insert(carLog);
			}
		}
		return res;
	}

}
